package com.xqls.thread;

import com.xqls.service.SokectService;
import com.xqls.util.CommonResult;
import com.xqls.util.ContextUtil;
import org.apache.log4j.Logger;

import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 发送操作指令
 */
public class SokectSendCyclicBarrierCallable implements Callable<Void> {
    private static Logger logger = Logger.getLogger(SokectSendCyclicBarrierCallable.class);
    private final CyclicBarrier barrier;
    private String methodName;
    private  final  Object[] params;
    private  StringBuffer resultMsg;
    private AtomicBoolean success;
    public SokectSendCyclicBarrierCallable(  CyclicBarrier barrier,
                                           String methodName, StringBuffer resultMsg, AtomicBoolean success, Object... params) {
        this.barrier = barrier;
        this.params=params;
        this.success=success;
        this.methodName=methodName;
        this.resultMsg=resultMsg;

    }

    public void run() {

    }

    @Override
    public Void call() throws Exception {

        try {
            SokectService sokectService= (SokectService) ContextUtil.getBean(SokectService.class);
            Class soket=sokectService.getClass();
            try{
                Method method=null;
                Method methlist[] = soket.getDeclaredMethods();
                for (int i = 0; i < methlist.length; i++) {
                    Method m = methlist[i];
                    if(m.getName().equals(methodName)){
                        method=m;
                    }
                }
                if(method!=null){


                    CommonResult result=(CommonResult)method.invoke(sokectService,params);
                    if(success.compareAndSet(true,true)){
                        if(!result.getIsSuccess()){
                            success.set(false);
                        }

                    }

                    if(!result.getIsSuccess()){
                        resultMsg.append(result.getResultMsg()).append("<br> ");
                    }
                }
                barrier.await();
            }catch (Exception e){
                throw e;
            }

        } catch ( Exception e) {
            logger.error("发送指令异常",e);
            resultMsg.append( "发送指令异常<br> ");
            success.set(false);
        }

        return null;
    }
}

